package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.User;
import com.zhentao.pojo.dto.WeChatCodeDTO;
import com.zhentao.pojo.vo.UsersLoginVO;
import com.zhentao.service.UserService;
import com.zhentao.mapper.UserMapper;
import com.zhentao.utils.HttpClientUtil;
import com.zhentao.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
* @author lenovo
* @description 针对表【user(用户基础信息表)】的数据库操作Service实现
* @createDate 2025-09-22 15:25:03
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    /** 微信 auth.code2Session 接口 */
    private final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final UserMapper userMapper;

    /**
     * 微信小程序授权登录
     *
     * @param code
     * @return
     */
    @Override
    public UsersLoginVO authWechat(WeChatCodeDTO code) {
        // 获取 openid
        String openId = getOpenId(code.getCode());

        // 查询用户是否已存在
        Long userId = userMapper.getUserByOpenId(openId);

        // 生成JWT
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("openId", openId);
        String token = JwtUtil.genToken(claims);

        if (userId == null) {
            // 如果用户不存在，则创建用户
            User user = User.builder()
                    .wxOpenId(openId)
                    .username("微信用户") // 提供默认用户名
                    .createTime(new Date())
                    .updateTime(new Date()) // 添加更新时间
                    .status(1) // 设置账户状态为激活
                    .isDeleted(0) // 设置为未删除
                    .build();
            userMapper.insert(user);

            return UsersLoginVO.builder()
                    .id(user.getUserId())
                    .token(token)
                    .username(user.getUsername())
                    .avatarUrl(user.getAvatarUrl())
                    .build();
        }

        // 用户已存在，查询完整用户信息
        User existingUser = userMapper.selectById(userId);
        return UsersLoginVO.builder()
                .id(Math.toIntExact(userId))
                .token(token)
                .username(existingUser.getUsername())
                .avatarUrl(existingUser.getAvatarUrl())
                .build();
    }

    /**
     * 通过微信登录code获取openId
     *
     * @param code 微信登录code
     * @return openId
     */
    public String getOpenId(String code) {
        // 添加参数
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", "wxde50c53482cfc83f");
        map.put("secret", "4cd7e10432a44b10e69658f3b7cbc3a3");
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        // 使用封装好的HttpClientUtil工具类发送请求
        String json = HttpClientUtil.doGet(WECHAT_LOGIN_URL, map);
        // 将JSON字符串转换为JSONObject对象
        JSONObject jsonObject = JSON.parseObject(json);
        // 从JSONObject中获取openid并返回
        return jsonObject.getString("openid");

    }
}




